package ranger
{
    import starling.display.Quad;
    import starling.display.Sprite;
    import starling.events.Event;
    import starling.text.TextField;
    
    public class CustomSprite extends Sprite
    {
        private var _quad:Quad; 
        private var _legend:TextField;
        private var _quadWidth:uint; 
        private var _quadHeight:uint;
        private var _red:Number = 0; 
        private var _green:Number = 0; 
        private var _blue:Number = 0;
        private var _rDest:Number; 
        private var _gDest:Number; 
        private var _bDest:Number;
        
        public function CustomSprite(width:Number, 
                                     height:Number, 
                                     color:uint=0x990000)
        {
            // reset the destination color component
            resetColors();
            
            // set the width and height
            _quadWidth = width; 
			_quadHeight = height;
            
            // when added to stage, activate 
            addEventListener(Event.ADDED_TO_STAGE, activate);
        }
        
        private function activate(event:Event):void 
        {
            // create a quad of the specified width
            _quad = new Quad(_quadWidth, _quadHeight);
            
            // add the legend
            _legend = new TextField(100, 20, "Hello Starling!", "Arial", 14, 0xFFFFFF);
            
            // add the children
            addChild(_quad); 
            addChild(_legend);
            
            // change the registration point
            pivotX = width >> 1;
            pivotY = height >> 1;
        }
        
        private function resetColors():void
        {
            // pick random color components
            _rDest = Math.random()*255; 
            _gDest = Math.random()*255; 
            _bDest = Math.random()*255;
        }
        
        public function update():void
        {
            // easing on the components
            _red -= (_red - _rDest)*.01; 
            _green -= (_green - _gDest)*.01; 
            _blue -= (_blue - _bDest)*.01;
            
            // assemble the color
            var color:uint = _red << 16 | _green << 8 | _blue; 
            _quad.color = color;
            
            // when reaching the color, pick another one
            if ( Math.abs( _red - _rDest) < 1 && Math.abs( _green - _gDest) < 1 && Math.abs( _blue - _bDest) )
            {
                resetColors();
            }
                
            // rotate it!
            rotation += .01;
        }
    }
}